package com.sense.feel.login.manager

import android.app.Activity
import android.content.Intent
import android.util.Log
import android.widget.Toast
import com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.firebase.auth.FacebookAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.sense.feel.login.manager.callback.OnFacebookLoginCallback
import com.sense.kukoo.lib_logger.LoggerManager

const val FACEBOOK_RESULT_CODE = 64206

object FacebookLoginManager {
    private const val TAG = "FacebookLoginManager"

    /**Firebase Google登录鉴权用户信息*/
    private var auth: FirebaseAuth? = null
    private lateinit var callbackManager: CallbackManager

    fun initFacebookLoginConfig(
        activity: Activity,
        onFacebookLoginCallback: OnFacebookLoginCallback
    ) {
        auth = Firebase.auth
        /**采用登录管理者注册回调*/
        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, object :
            FacebookCallback<LoginResult> {
            override fun onCancel() {
                LoggerManager.e(TAG, "onCancel")
                onFacebookLoginCallback.onCancel()
            }

            override fun onSuccess(result: LoginResult) {
                var accessToken = result.accessToken
                LoggerManager.e(TAG, "handleFacebookAccessToken:$accessToken")
                handleFacebookAccessToken(activity, accessToken, onFacebookLoginCallback)
            }
            override fun onError(error: FacebookException) {
                LoggerManager.e(TAG, "error.message=" + error.message)
                error.message?.let { onFacebookLoginCallback.onFail(it) }
            }
        })
    }

    /**使用登录管理者登录*/
    fun login(activity: Activity) {
        LoggerManager.e(TAG, "login")
        var list = mutableListOf("public_profile")
        list.add("email")
        LoginManager.getInstance()
            .logInWithReadPermissions(activity, list)
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleFacebookAccessToken(
        activity: Activity,
        token: AccessToken,
        onFacebookLoginCallback: OnFacebookLoginCallback
    ) {

        val credential = FacebookAuthProvider.getCredential(token.token)
        auth?.signInWithCredential(credential)
            ?.addOnCompleteListener(activity) { task ->
                if (task.isSuccessful) {
                    LoggerManager.e(TAG, "signInWithCredential:success")
                    val user = auth?.currentUser
                    user?.let {
                        onFacebookLoginCallback.onSuccess(it)
                    }
                    LoggerManager.e(TAG, "displayName=" + user?.displayName)
                    LoggerManager.e(TAG, "tenantId=" + user?.tenantId)
                    LoggerManager.e(TAG, "emaile=" + user?.email)
                    LoggerManager.e(TAG, "phoneNumber=" + user?.phoneNumber)
                    LoggerManager.e(TAG, "providerId=" + user?.providerId)
                    LoggerManager.e(TAG, "uid=" + user?.uid)
                } else {
                    LoggerManager.e(TAG, "signInWithCredential:failure", task.exception)
                    Toast.makeText(
                        activity, "Authentication failed.",
                        Toast.LENGTH_SHORT
                    ).show()
                    onFacebookLoginCallback.onFail(task.exception.toString())
                }
            }
    }

    fun loginOut() {
        if (isLogin())
            auth?.signOut()
    }

    private fun isLogin(): Boolean {
        auth = Firebase.auth
        val user = auth?.currentUser
        return user != null
    }

}